<template>
    <section id="ex-change-page">
        <article class="top">
            <w-row>
                <w-cell align="right">
                    <p style="text-align: center;">
                        <img class="userImg" :src='HeadImg' />
                    </p>
                </w-cell>
                <w-cell direction="column" align="center">
                    <p class="name">姓名：{{Name}}</p>
                    <p class="level">{{Integral>=100 ? '麻醉能手' : '麻醉新手'}}</p>
                    <p class="time">注册时间：{{RegistTime | changeDateFormat }}</p>
                </w-cell>
            </w-row>
        </article>
        <article class="center">
            <p class="title">你可兑换的商品</p>
            <section class="goods">
                <h6>目前积分：{{Integral}}分</h6>
                <w-row style="flex-wrap: wrap; justify-content: space-between;">
                    <w-cell class="good-detail" v-for="(item,index) in goodList" :key="index" style="width: 8rem;flex:none;">
                        <w-row>
                            <w-cell direction="column" align="center" class="gimg">
                                <img :src='item.GoodImg' style="width: 100%; height:100px;"/>
                                <div class="g-msg">
                                    <p class="gname">{{item.Name}}</p>
                                    <p class="gjf">积分：{{item.RequireJF}}</p>
                                    <p class="gbtn">
                                        <w-button size="small" type="primary" :plain="plain" :bgColor="bgColor" fontColor="#ffffff" :block="isBlock" borderColor="borderColor"
                                            @click="changeGood(item.ID,item.RequireJF)">兑换</w-button>
                                    </p>
                                </div>
                            </w-cell>
                        </w-row>
                    </w-cell>
                </w-row>
            </section>
        </article>
        <article ref="postDialog" v-show="false">
            <w-row>
                <w-cell>
                    <w-field name="postName" v-model="postName" label-width="0" height="40" placeholder="姓名" class="inp-row" style="width:100%;">
                        <w-row slot="label">
                            <w-cell>
                                <i class='login-mobile-icon'></i>
                            </w-cell>
                            <w-cell class="line">
                                <span></span>
                            </w-cell>
                        </w-row>
                    </w-field>
                </w-cell>
            </w-row>
            <w-row>
                <w-cell>
                    <w-field name="postMobile" v-model="postMobile" label-width="0" height="40" placeholder="联系方式" class="inp-row" style="width:100%;">
                        <w-row slot="label">
                            <w-cell>
                                <i class='login-mobile-icon'></i>
                            </w-cell>
                            <w-cell class="line">
                                <span></span>
                            </w-cell>
                        </w-row>
                    </w-field>
                </w-cell>
            </w-row>
            <w-row>
                <w-cell>
                    <w-field name="postAddress" v-model="postAddress" label-width="0" height="40" placeholder="邮寄地址" class="inp-row" style="width:100%;">
                        <w-row slot="label">
                            <w-cell>
                                <i class='login-mobile-icon'></i>
                            </w-cell>
                            <w-cell class="line">
                                <span></span>
                            </w-cell>
                        </w-row>
                    </w-field>
                </w-cell>
            </w-row>
        </article>
    </section>
</template>

<script>
    import Vue from 'vue'
    import {
        mapGetters,
        mapActions
    } from 'vuex';
    import axios from 'axios'
    //let user = JSON.parse(localStorage.getItem('userMsg'));
    export default {
        name: "exchange",
        data() {
            return {
                isBlock: true,
                bgColor: "#005ba8",
                plain: false,
                openID:'',

                Name: '',
                Integral: '',
                HeadImg: '',
                RegistTime: '',

                postAddress: '',
                postMobile: '',
                postName: ''
            }
        },
        filters: {
            changeDateFormat: function (val) {
                if (val != null) {
                    var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
                    //月份为0-11，所以+1，月份小于10时补个0
                    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                    return date.getFullYear() + "-" + month + "-" + currentDate;
                }
                return "";
            }
        },
        computed: {
            ...mapGetters({
                goodList: 'goodList'
            }),
        },
        mounted() {

            // if(localStorage.openID == "" || localStorage.openID == undefined || localStorage.openID == "undefined") {
            //      axios.get('/wx/getcodeurl', {　
            //         params: { 'Appid': 'wx27a54ca734af2cf8','redirect_uri': 'http://zqdn.aegis-s.com/wx/getwxusertochange' }
            //           }).then(function(response) {
            //             //引导用户根据地址获取code
            //             let wxobj = this.GetRequest(response.data);
            //             let openid = wxobj["/ex/change?openid"];
            //             localStorage.openID = openid;
            //             location.reload();
            //           }).catch(function(error) {　　
            //             console.log(error);　
            //     });
            // } else {

            //let openid = localStorage.openID;
            let wxobj = this.GetRequest(location.hash);
            let openid = wxobj["/ex/change?openid"];
            //let openid = "oGqC5jgtFzCVXPrTQafjapEzX1iI";
            this.openID=openid;
            this.checkUserInfo(openid).then((response) => {
                console.log(openid);
                let _res = response[0];
                console.log(response);
                if (_res.msg == '0') {
                    Wui.Toast.show('尚未注册，请先注册', 'middle');
                    setTimeout(function () {
                        location.href = '#/registtpl';
                    }, 1000);
                } else if (_res.msg == '1') {
                    //user = response.data.userInfo;
                    this.HeadImg = _res.userInfo.HeadImg;
                    this.Name = _res.userInfo.Name;
                    this.Integral = _res.userInfo.Integral;
                    this.RegistTime = _res.userInfo.CreatedTime;

                    //纪录用户信息
                    var _user = JSON.stringify(_res.userInfo);
                    localStorage.setItem('userMsg', _res._user);
                    this.getGoodList();

                } else {
                    Wui.Toast.show(_res.msg, 'middle');
                }
            });
            //}
        },
        methods: {
            ...mapActions([
                'getGoodList',
                'saveChangeLog',
                'setLoading',
                'checkUserInfo',
                'getAddressInfo'
            ]),
            changeGood: function (id, RequireJF) {
                if (this.Integral < RequireJF) {
                    window.Wui.Toast.show('积分不足，无法兑换', 'middle');
                    return false;
                }
                let me = this;
                debugger;
                me.getAddressInfo({openid:me.openID}).then((data) => {
                debugger;
                    if (data.Result == "success") {
                        console.log(data);
                        // me.postAddress = data.address;
                        // me.postMobile = data.mobile;
                        // me.postName = data.name;
                        //document.getElementsByName('postAddress')[1].value = localStorage.lastAddress
                        Wui.Dialog.show({
                            title: '邮寄地址',
                            content: me.$refs.postDialog.innerHTML,
                            width: 300,
                            height: 200,
                            showClose: true,
                            buttons: [{
                                text: '确认',
                                class: 'btn-cutom-blue',
                                action() {
                                    //积分兑换
                                    this.show();
                                    debugger;
                                    
                                    if (document.getElementsByName('postName')[1].value.replace(
                                            /\s+$|^\s+/g, "") == '') {
                                        window.Wui.Toast.show('请输入联系人', 'middle');
                                        return false;
                                    }
                                    if (document.getElementsByName('postMobile')[1].value.replace(
                                            /\s+$|^\s+/g, "") == '') {
                                        window.Wui.Toast.show('请输入联系人手机号', 'middle');
                                        return false;
                                    }
                                    if (document.getElementsByName('postAddress')[1].value.replace(
                                            /\s+$|^\s+/g, "") == '') {
                                        window.Wui.Toast.show('请输入邮寄地址', 'middle');
                                        return false;
                                    }

                                    let params = {
                                        GID: id,
                                        Address: document.getElementsByName('postAddress')[1].value,
                                        Name: document.getElementsByName('postName')[1].value, //me.postName,
                                        Mobile: document.getElementsByName('postMobile')[1].value,
                                        RequireJF: RequireJF,
                                        OpenID: localStorage.openID
                                    }
                                    alert(me.postAddress);
                                    me.setLoading(true);
                                    me.saveChangeLog(params).then((res) => {
                                        me.setLoading(false);
                                        this.hide();
                                        if (res.Result == "success") {
                                            //记录最近一次邮寄地址
                                            localStorage.lastAddress = params.Address;
                                            localStorage.removeItem("userMsg");
                                            var _user = JSON.stringify(res.userInfo)
                                            localStorage.setItem('userMsg', _user);
                                            me.Integral = JSON.parse(localStorage.getItem(
                                                    'userMsg'))
                                                .Integral;
                                        }
                                    });
                                }
                            }]
                        });
                    }
                });
            },
            GetRequest: function (url) {
                var url = decodeURI(url); //获取url中"?"符后的字串   
                var theRequest = {};
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    let strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            },
        }
    }
    //  window.addEventListener("popstate", function(e) {  //回调函数中实现需要的功能
    //         Vue.prototype.$wx.closeWindow();
    //  }, false);
</script>

<style lang="scss" scoped>
    #ex-change-page {
        height: 100%;
        background: #f2f2f2;
        .top {
            width: 18.75rem;
            background: url('../../assets/img/ex/banner.png') center no-repeat;
            background-size: 100% auto;
            padding: 1rem 0 1rem 0;
            img {
                width: 70%;
            }
            .name,
            .level {
                color: #005ba8;
                font-weight: bold;
                font-size: 0.8rem;
                text-align: left;
                width: 9rem;
                line-height: 1.3rem;

            }
            .time {
                font-size: 0.7rem;
                text-align: left;
                width: 9rem;
                line-height: 1.3rem;
            }
        }
        .center {
            .title {
                text-align: center;
                padding: 0.5rem 0;
                color: #005ba8;
                font-weight: bold;
                font-size: 0.8rem;
            }
            .goods {
                background: #fff;
                padding: 0 1rem;
                h6 {
                    text-align: center;
                    font-weight: 200;
                    padding: 0.5rem 0;
                }
                .good-detail {
                    border: 1px solid #efefef;
                    border-radius: 10px;
                    margin-bottom: 1rem;
                }
                .gimg {
                    img {
                        width: 7.225rem;
                    }
                    .g-msg {
                        text-align: center;
                        font-size: 0.6rem;
                        padding-bottom: 0.6rem;
                        p {
                            line-height: 1rem;
                        }
                    }
                }
            }
        }
        .userImg {
            border-radius: 50px;
        }
    }
</style>
